import { loginAPI } from '@/api/user'
import { removeCookies, setCookies, getCookies } from '@/utils/auth'
const state = {
  token: getCookies('admin-Token'),
  userInfo: getCookies('userInfo')
}
const mutations = {
  // 持久化存储token
  setToken(state, payload) {
    setCookies('admin-Token', payload)
    state.token = payload
  },
  // 删除token 以及 userInfo
  removeToken(state) {
    removeCookies('admin-Token')
    removeCookies('userInfo')
    state.token = null
    state.userInfo = null
  },
  // 持久化存储用户信息
  setUserInfo(state, payload) {
    setCookies('userInfo', payload)
    state.userInfo = payload
  }
}
const actions = {
  // 登录
  actionLogin(context, payload) {
    return loginAPI(payload)
      .then(({ data }) => {
        data.data && context.commit('setToken', data.data.token.token)
        data.data && context.commit('setUserInfo', data.data.user)
        return data
      }).catch(err => {
        return Promise.reject(err)
      })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

